package net.sahv.bdyz.util;

import java.io.File;
import java.io.IOException;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
@Component("imgUtil")
public class ImgUtil {
	private Logger log = Logger.getLogger(ImgUtil.class);
	
	

	/**
	 * 
	 * @param request
	 * @param savePath 保存文件的地址 goods/xxxx  
	 *  				 会存放在/upload/goods/xxxx目录下
	 * @return
	 */
	public String uploadImg(HttpServletRequest request,String savePath,String fileName){
		String newImgFilePath = "";
		try {
			// 判断是否有文件流
			boolean isMultipart = ServletFileUpload.isMultipartContent(request);
			if (!isMultipart) {
				return "1";
			}
			MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;//流的数据*
			MultipartFile imgFile = multipartRequest.getFile(fileName);// 获取名字为fileName的文件流*
			if(imgFile.getSize()==0){
				return null;
			}
			// 1、设置保存位置
			String filePath = request.getSession().getServletContext().getRealPath("/upload");// 保存文件路径
			//String filePath = request.getSession().getServletContext().getRealPath("/upload/"+savePath);// 后来修改,还没修改好
			// 2、判断文件夹是否存在 否：创建；是：保存在文件夹下
			File uploadFile = new File(filePath);
			if (!uploadFile.exists()) {
				uploadFile.mkdirs();//包括父目录*
			}
			// 3、设置要保存的路径及名称
			if (imgFile != null) {
				newImgFilePath = updateHeadPicInfo(filePath, imgFile);
			}
		} catch (Exception e) {
			log.info(e.getMessage());
			e.printStackTrace();
		}
		// 返回结果
		return newImgFilePath;
		//return newImgFilePath;
	}
	protected String updateHeadPicInfo(String filePath, MultipartFile file)
			throws IllegalStateException, IOException {
		String newFileName = "";
		try {
			String newHeadImgName = "";// 重新设置要保存头像的文件名
			// 获取当前时间
			Date d = new Date();
			newHeadImgName += ""+d.getTime()+((int)(Math.random()*9000+1000)) + ".png";
			newFileName = newHeadImgName;
			File targetHeadFile = new File(filePath, newHeadImgName);//File(目录,文件名)
			file.transferTo(targetHeadFile);//把文件流转换到文件里名字还是newFileName*
		} catch (Exception e) {
			e.printStackTrace();
		}
		return newFileName;
	}
	
	public String getBasePath(){
		HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();  
		return request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort();
	}
}
